<template>
  <PageDialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <NewPageFilter
      v-model:query="filterInfo.query.queryMap"
      :query-more-json="true"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
      :clearType="clearType"
    >
      <template v-slot:filter-stockSearchKey>
        <el-input
          v-model="filterInfo.stockSearchKey"
          placeholder="请输入入库批次\供应商名称"
          @change="changeStockSearchKey"
        />
      </template>
    </NewPageFilter>
    <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
      <DialogTable
        ref="resourceTable"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :rowKey="rowKey"
        :highlight-row="highlightRow"
        :checkedRowList="checkedRowList"
        :reserve-selection="true"
        :check-box="checkBox"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-editQty="scope">
          <el-form-item
            v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
            class="margin-bottom"
            @click.stop=""
          >
            <div class="page-table-input-number-wrapper">
              <div class="page-table-input-number-left">
                <div class="page-table-input-number-item">
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.largeUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="
                        scope.row.qtyOperateMode === 0 ||
                        scope.row.qtyOperateMode === 2
                          ? 0
                          : systemConfig.qty_show_precision
                      "
                      :min="0"
                      :max="largeMax(scope.row)"
                      @change="changeLarge($event, scope.row)"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.unitName }}
                  </div>
                </div>
                <div
                  v-if="
                    scope.row.unitConvertCoefficient > 1 &&
                    scope.row.qtyOperateMode === 2
                  "
                  class="page-table-input-number-item"
                >
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.smallUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="0"
                      :min="0"
                      :max="smallMax(scope.row)"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.calcUnitName }}
                  </div>
                </div>
              </div>
              <div
                v-if="scope.row.qtyOperateMode === 2"
                class="page-table-input-number-right"
              >
                {{ $fn.qtyFormatter(scope.row.editQty) }}
              </div>
            </div>
          </el-form-item>
          <span
            v-else-if="scope.row.codeType === 2 || scope.row.codeType === 3"
            >{{ $fn.qtyFormatter(scope.row.editQty) }}</span
          >
        </template>
        <template v-slot:col-storeBatchNumber="scope">
          <StoreBatchNumberTag :row="scope.row" />
        </template>
      </DialogTable>
    </el-form>
  </PageDialog>
</template>
<script setup name="SelectBatch">
import { getCustomizeSetting } from '@/api/customize'
import { getDepotStockCustomizeListPage } from '@/api/stock.js'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  showPrice: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  tableKey: {
    type: String,
    default: '',
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
  checkedRowList: {
    type: Array,
    default: () => {
      return []
    },
  },
  saveEmpty: {
    type: Boolean,
    default: false,
  },
  codeType: {
    type: Number,
  },
})
const clearType = ref(true)
// 过滤相关配置
const filterInfo = ref({
  query: {
    page: true,
    customizeUserVO: {},
    sortString: '',
    excludeQueryList:
      props.query.excludeQueryList && props.query.excludeQueryList.length
        ? [...props.query.excludeQueryList]
        : [],
    queryMap: {
      ...props.query.queryMap,
    },
    queryParams: {
      ...props.query.queryParams,
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  copyQueryMap: {},
  stockSearchKey: props.query.queryParams.stockSearchKey,
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
// 弹窗相关
const dialogInfo = ref({
  title: '新增批次信息',
  width: '50%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: !props.saveEmpty,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref([])
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        if (row.codeType === 1 || row.codeType === 4) {
          let smallUnitQty = parseFloat(row.smallUnitQty || 0)
          let unitConvertCoefficient = row.unitConvertCoefficient || 1
          let largeUnitQty = parseFloat(row.largeUnitQty || 0)
          let editCalcQty = proxy.$fn.accAdd(
            proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
            smallUnitQty
          )
          let editQty = proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
          row.editCalcQty = editCalcQty
          row.editQty = editQty
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(editCalcQty, row.price),
            unitConvertCoefficient
          )
        }
      })
    }
  },
  {
    deep: true,
  }
)
watch()
setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    editQty: {
      label: '数量',
      value: 'editQty',
      type: 'slot',
      componentType: 'number',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function changeStockSearchKey(val) {
  filterInfo.value.query.queryParams.stockSearchKey = val
  search()
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQueryMap)
  filterInfo.value.stockSearchKey = ''
  filterInfo.value.query.queryParams.stockSearchKey = ''
  search()
}
// 获取列表
function getList() {
  proxy.$nextTick(() => {
    tableInfo.value.refresh = Math.random()
  })
}
function search() {
  proxy.$nextTick(() => {
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  })
}
function save() {
  if (selectRow.value && selectRow.value.length) {
    selectRow.value.forEach((item) => {
      item.calcQty = item.editCalcQty
      item.qty = item.editQty
      item.depotStockIdClone = item.depotStockId
      item.depotStockId = item.id
    })
  }
  handleClose()
  emits('callback', selectRow.value)
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.value.btList[1].disabled = !(data && data.id)
      }
      break
    case 'tableCheck':
      selectRow.value = data
      if (!props.saveEmpty) {
        dialogInfo.value.btList[1].disabled = !data.length
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function getCustomize() {
  let param = { tableKey: props.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      tableInfo.value.fieldList.forEach((item) => {
        if (props.codeType === 1 || props.codeType === 4) {
          if (
            item.value === 'uniqueCode' ||
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode'
          ) {
            item.hidden = true
          }
          if (item.value === 'qrCode') {
            item.hidden = true
          }
        } else if (props.codeType === 2) {
          if (
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode'
          ) {
            item.hidden = true
          }
        } else if (props.codeType === 3) {
          if (item.value === 'uniqueCode') {
            item.hidden = true
          }
        }
        if (item.value === 'storeBatchNumber') {
          item['type'] = 'slot'
        }
      })
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        if (props.codeType === 1 || props.codeType === 4) {
          if (
            item.value === 'uniqueCode' ||
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode'
          ) {
            item.show = false
          }
          if (item.value === 'qrCode') {
            item.show = false
          }
        } else if (props.codeType === 2) {
          if (
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode'
          ) {
            item.show = false
          }
        } else if (props.codeType === 3) {
          if (item.value === 'uniqueCode') {
            item.show = false
          }
        }
        item.event = search
      })
      let stockSearchKey = {
        slot: true,
        value: 'stockSearchKey',
      }
      filterInfo.value.searchList.unshift(stockSearchKey)
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query
      )
      tableInfo.value.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss"></style>
